package com.hpq.user.controller;

import com.hpq.user.service.WxMsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

/**
 *微信api交互接口
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("wx/portal/public")
@Api(tags = "微信相关公共接口")
public class WxPortalController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpMessageRouter wxMpMessageRouter;
    @Autowired
    private WxMsgService wxMsgService;

    /**
     * 微信公众号授权验证
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping(produces = "text/plain;encoding =UTF-8")
    @ApiOperation(value = "微信服务器认证")
    public String authGet(@RequestParam(value = "signature", required = true)String signature,
                          @RequestParam(value = "timestamp", required = true)String timestamp,
                          @RequestParam(value = "nonce", required = true)String nonce,
                          @RequestParam(value = "echostr", required = true)String echostr){
            log.info("\n接受来自微信服务器的认证消息：[{},{},{},{}]", signature, timestamp, nonce, echostr);
            if(StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)){
                throw new IllegalArgumentException("请求参数非法，请核实!");
            }
            if(wxMpService.checkSignature(timestamp, nonce, signature)){
                return echostr;
            }
            return "非法请求";
    }

    /**
     *  授权回调
     * @param code
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/callBack")
    @ApiOperation(value = "授权回调接口")
    public RedirectView callBack(@RequestParam String code) throws WxErrorException {
        // 根据code获取accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        // 根据accessToken获取用户信息
        WxOAuth2UserInfo userInfo =  wxMpService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
        log.info("用户信息：" + userInfo);
        //同步授权到的用户信息到数据库
        wxMsgService.saveAuthorize(userInfo);
        //重定向到网站首页
        return new RedirectView("https://www.mallchat.cn");
    }

    /**
     *  接收微信消息
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @param openid
     * @param encType
     * @param msgSignature
     * @return
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    @ApiOperation(value = "接收微信消息")
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.wxMpMessageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }


}
